<template>
  <el-select
    v-if="type === 'select'"
    v-model="selectedValue"
    :placeholder="placeholder"
    :disabled="disabled"
    clearable
    :style="style"
    @change="handleChange"
  >
    <el-option v-for="option in options" :key="option.id as number" :label="option.dictLabel" :value="option.dictValue" />
  </el-select>

  <el-radio-group v-else-if="type === 'radio'" v-model="selectedValue" :disabled="disabled" :style="style" @change="handleChange">
    <el-radio v-for="option in options" :key="option.dictValue" :value="option.dictValue">
      {{ option.dictLabel }}
    </el-radio>
  </el-radio-group>

  <el-checkbox-group v-else-if="type === 'checkbox'" v-model="selectedValue" :disabled="disabled" :style="style" @change="handleChange">
    <el-checkbox v-for="option in options" :key="option.dictValue" :value="option.dictValue">
      {{ option.dictLabel }}
    </el-checkbox>
  </el-checkbox-group>
</template>

<script setup lang="ts">
import useDictStore from '@/stores/dict'
import type { ItemFormInt } from '@/api/system/dictItem/types'
const dictStore = useDictStore()

const props = defineProps({
  code: {
    type: String,
    required: true
  },
  modelValue: {
    type: [String, Number, Array],
    required: false
  },
  type: {
    type: String,
    default: 'select',
    validator: (value: string) => ['select', 'radio', 'checkbox'].includes(value)
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  style: {
    type: Object,
    default: () => {
      return {
        width: '300px'
      }
    }
  }
})

const emit = defineEmits(['update:modelValue'])

const options = ref<ItemFormInt[]>([])

const selectedValue = ref<any>(
  typeof props.modelValue === 'string' || typeof props.modelValue === 'number'
    ? props.modelValue
    : Array.isArray(props.modelValue)
      ? props.modelValue
      : undefined
)

// 监听 modelValue 和 options 的变化
watch(
  [() => props.modelValue, () => options.value],
  ([newValue, newOptions]) => {
    if (newOptions.length > 0 && newValue !== undefined) {
      if (props.type === 'checkbox') {
        selectedValue.value = Array.isArray(newValue) ? newValue : []
      } else {
        const matchedOption = newOptions.find((option) => String(option.dictValue) === String(newValue))
        selectedValue.value = matchedOption?.dictValue
      }
    } else {
      selectedValue.value = undefined
    }
  },
  { immediate: true }
)

// 监听 selectedValue 的变化并触发 update:modelValue
function handleChange(val: any) {
  emit('update:modelValue', val)
}

// 获取字典数据
onMounted(async () => {
  options.value = await dictStore.getDictItems(props.code)
})
</script>
